const { ethers } = require("hardhat");

async function main() {
  console.log("开始部署茶叶溯源系统智能合约...");

  // 获取部署账户
  const [deployer] = await ethers.getSigners();
  console.log("部署账户:", deployer.address);
  
  // 获取账户余额
  const balance = await deployer.provider.getBalance(deployer.address);
  console.log("账户余额:", ethers.formatEther(balance), "ETH");

  // 部署主合约
  console.log("\n正在部署 TeaTraceabilitySystem 合约...");
  const TeaTraceabilitySystem = await ethers.getContractFactory("TeaTraceabilitySystem");
  const teaSystem = await TeaTraceabilitySystem.deploy();
  
  await teaSystem.waitForDeployment();
  const teaSystemAddress = await teaSystem.getAddress();
  
  console.log("✅ TeaTraceabilitySystem 合约部署成功!");
  console.log("合约地址:", teaSystemAddress);

  // 获取子合约地址
  console.log("\n获取子合约地址...");
  const systemInfo = await teaSystem.getSystemInfo();
  
  console.log("✅ AccessControl 合约地址:", systemInfo.accessControlAddr);
  console.log("✅ TeaBatch 合约地址:", systemInfo.teaBatchAddr);

  // 验证合约部署
  console.log("\n验证合约部署...");
  const healthCheck = await teaSystem.healthCheck();
  console.log("系统健康检查:", healthCheck ? "✅ 正常" : "❌ 异常");

  // 获取系统统计信息
  const stats = await teaSystem.getSystemStats();
  console.log("\n系统统计信息:");
  console.log("- 总用户数:", stats.totalUsers.toString());
  console.log("- 总批次数:", stats.totalBatches.toString());
  console.log("- 总交易数:", stats.totalTransactions.toString());
  console.log("- 部署时间:", new Date(Number(stats.deployedAt) * 1000).toLocaleString());

  // 保存部署信息到文件
  const deploymentInfo = {
    network: hre.network.name,
    chainId: (await deployer.provider.getNetwork()).chainId.toString(),
    contracts: {
      TeaTraceabilitySystem: teaSystemAddress,
      AccessControl: systemInfo.accessControlAddr,
      TeaBatch: systemInfo.teaBatchAddr
    },
    deployer: deployer.address,
    deployTime: new Date().toISOString(),
    gasUsed: {
      // 这些值会在实际部署时填入
    }
  };

  console.log("\n📋 部署信息摘要:");
  console.log("=".repeat(50));
  console.log(`网络: ${deploymentInfo.network}`);
  console.log(`链ID: ${deploymentInfo.chainId}`);
  console.log(`主合约: ${deploymentInfo.contracts.TeaTraceabilitySystem}`);
  console.log(`部署者: ${deploymentInfo.deployer}`);
  console.log(`部署时间: ${deploymentInfo.deployTime}`);
  console.log("=".repeat(50));

  // 创建一些测试用户 (仅在开发环境)
  if (hre.network.name === "hardhat" || hre.network.name === "localhost") {
    console.log("\n🧪 创建测试用户...");
    
    const accounts = await ethers.getSigners();
    
    // 注册茶农
    if (accounts.length > 1) {
      await teaSystem.registerUser(
        accounts[1].address,
        "TestFarmer",
        1 // UserRole.FARMER
      );
      console.log("✅ 测试茶农已注册:", accounts[1].address);
    }

    // 注册物流方
    if (accounts.length > 2) {
      await teaSystem.registerUser(
        accounts[2].address,
        "TestLogistics",
        2 // UserRole.LOGISTICS
      );
      console.log("✅ 测试物流方已注册:", accounts[2].address);
    }

    // 注册商家
    if (accounts.length > 3) {
      await teaSystem.registerUser(
        accounts[3].address,
        "TestMerchant",
        3 // UserRole.MERCHANT
      );
      console.log("✅ 测试商家已注册:", accounts[3].address);
    }

    console.log("\n🎉 测试环境初始化完成!");
  }

  console.log("\n🚀 茶叶溯源系统部署成功!");
  console.log("系统版本:", systemInfo.version);
  console.log("可以开始使用系统进行茶叶溯源了!");

  return {
    teaSystem: teaSystemAddress,
    accessControl: systemInfo.accessControlAddr,
    teaBatch: systemInfo.teaBatchAddr
  };
}

// 错误处理
main()
  .then((deploymentAddresses) => {
    console.log("\n✅ 部署完成，合约地址：");
    console.log(JSON.stringify(deploymentAddresses, null, 2));
    process.exit(0);
  })
  .catch((error) => {
    console.error("\n❌ 部署失败:");
    console.error(error);
    process.exit(1);
  });